import * as XLSX from "xlsx";


/**
 * 导出模板
 * @param headers   头字段列表
 * @param sheetName  文件名｜表名
 */
export function downloadExcelTemplate(headers, sheetName) {
  let aoa = [
    headers
  ];

  let sheet = XLSX.utils.aoa_to_sheet(aoa);

  let sheetArr = [sheet];
  let sheetNameArr = [sheetName];

  let blob = sheet2blob(sheetArr, sheetNameArr);
  let fileName = sheetName + '导入模板.xlsx';
  if ('download' in document.createElement('a')) { // 非IE下载
    let elink = document.createElement('a')
    elink.download = fileName
    elink.style.display = 'none'
    elink.href = URL.createObjectURL(blob)
    document.body.appendChild(elink)
    elink.click()
    URL.revokeObjectURL(elink.href) // 释放URL 对象
    document.body.removeChild(elink)
  } else { // IE10+下载
    navigator.msSaveBlob(blob, fileName)
  }
}


 function sheet2blob (sheetArr, sheetNameArr) {
  // 将一个sheet转成最终的excel文件的blob对象，然后利用URL.createObjectURL下载
  const workbook = {
    SheetNames: sheetNameArr,
    Sheets: []
  };

  sheetArr.some((item, i) =>{
    workbook.Sheets[sheetNameArr[i]] = item;
  });

  // 生成excel的配置项
  const wopts = {
    bookType: 'xlsx', // 要生成的文件类型
    bookSST: false, // 是否生成Shared String Table，官方解释是，如果开启生成速度会下降，但在低版本IOS设备上有更好的兼容性
    type: 'binary'
  };
  const wbout = XLSX.write(workbook, wopts);
  // 字符串转ArrayBuffer
  function s2ab(s) {
    let buf = new ArrayBuffer(s.length);
    let view = new Uint8Array(buf);
    for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  return new Blob([s2ab(wbout)], { type: "application/octet-stream" });
}
